package com.onenine.app.danmu;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.onenine.app.model.BarrageItem;
import com.onenine.app.utils.CHelper;
import com.onenine.common.util.SizeUtils;
import com.onenine.glide.GlideApp;

import master.flame.danmaku.danmaku.model.BaseDanMu;
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer;
import master.flame.danmaku.ui.widget.DanMuView;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class CacheStufferAdapter extends BaseCacheStuffer.Proxy {

    private Context mContext;
    private DanMuView mDanMuView;
    private int mAvatarSize;

    public CacheStufferAdapter(Context context, DanMuView danMuView) {
        mContext = context;
        mDanMuView = danMuView;
        mAvatarSize = SizeUtils.dp2px(50);
    }

    @Override
    public void prepareDrawing(final BaseDanMu danMu, boolean fromWorkerThread) {
        if (!(danMu.tag instanceof BarrageItem)) {
            return;
        }
        mDanMuView.post(new Runnable() {
            @Override
            public void run() {
                BarrageItem barrageItem = ((BarrageItem) danMu.tag);
                if (barrageItem == null) {
                    return;
                }
                GlideApp.with(mContext).load(CHelper.getOssThumbImageUrl(barrageItem.getPhoto(), mAvatarSize))
                        .transition(withCrossFade())
                        .transform(new CircleCrop()).into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition transition) {
                        if (drawable != null) {
                            barrageItem.setAvatarDrawable(drawable);
                            danMu.tag = barrageItem;
                            mDanMuView.invalidateDanmaku(danMu, true);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void releaseResource(BaseDanMu danmaku) {
        BarrageItem barrageItem = (BarrageItem) danmaku.tag;
        if (barrageItem != null) {
            barrageItem.setTouchClick(false);
//            barrageItem.setAvatarDrawable(null);
        }
    }

}
